<?php

namespace app\index\service;

use app\common\model\Consulting;
use app\common\model\ConsultingServer;
use app\index\dao\ConsultingDao;
use app\index\model\UM as UM;
use app\index\traits\ConsultingTrait;
use app\index\traits\MutedTrait;

/**
 * Class RandomConsultingService
 * @package app\index\service
 */
class RandomConsultingService
{
    use MutedTrait;
    use ConsultingTrait;

    // dao
    private ConsultingDao $consultingDao;
    private FreeConsultingService $freeConsultingService;

    public function __construct(ConsultingDao $consultingDao, FreeConsultingService $freeConsultingService)
    {
        $this->consultingDao = $consultingDao;
        $this->freeConsultingService = $freeConsultingService;
    }

    /**
     * 创建极速咨询咨询（随机匹配律师）
     * @param UM $user
     * @param array $params
     * @return  Consulting
     */
    public function add(UM $user, array $params): Consulting
    {
        $memberId = $user->id;

        $lawyerId = 0;
        $initMatchType = Consulting::MATCH_TYPE_RANDOM;
        $matchType = Consulting::MATCH_TYPE_SVIP;
        $pagePath = $params['pagePath'] ?? '';
        $categoryId = $params['categoryId'] ?? '0';
        $consultingFormId = $params['consultingFormId'] ?? '0';

        // 渠道链路
        ['pf' => $pf, 'chain' => $chain, 'promotionGroupId' => $promotionGroupId] = getChainParams();

        // 咨询创建者
        $this->checkConsultingCreator($user);

        // 禁言
        $this->checkMuted($user);

        // 咨询创建次数
        $this->checkConsultingTimes($user);

        // 免费咨询服务
        $freeServer = ConsultingServer::where('serverType', ConsultingServer::FREE)->find();

        // 创建咨询
        $record = $this->freeConsultingService->addConsulting($freeServer, null, Consulting::BT_RANDOM, $memberId, $initMatchType, $matchType, $lawyerId,
            '0', '0', '', $consultingFormId, $categoryId, $user->provinceId, $user->cityId, $pf, $chain, $promotionGroupId, $pagePath);

        if ($record->isNew == 1) {
            // 极速咨询创建事件
            event('RandomConsultingCreated', $record);
        }

        return $record;
    }


}
